import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import useLoginStore from '@/store/user/index.js'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main/home'
    },
    {
      path: '/login',
      component: () => import('@/views/login/login.vue')
    },

    {
      path: '/main',
      name: 'main',
      redirect: '/main/home',
      component: () => import('@/views/main.vue'),
      children: [
        {
          path: '/main/home',
          name: 'home',
          component: () => import('@/views/home/home.vue')
        },
        {
          path: '/main/person',
          name: 'person',
          component: () => import('@/views/person/person.vue')
        },

        {
          path: '/main/system',
          name: 'system',
          component: () => import('@/views/system/index.vue'),
          children:[
            {
              path: 'user',
              name: 'user',
              component:() => import('@/views/system/user/user.vue')
            },

            {
              path: 'role',
              name: 'role',
              component:() =>import('@/views/system/role/role.vue')
            },

            {
              path: 'menu',
              name: 'menu',
              component:() =>import('@/views/system/menu/menu.vue')
            },

            {
              path: 'dept',
              name: 'dept',
              component:() =>import('@/views/system/dept/dept.vue')
            },
          ]
        },


      ]
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('@/not-found/not-found.vue')
    }
  ]
})

//路由鉴权
//进度条的加载小圆球不要
NProgress.configure({ showSpinner: false })

//定义不需要登录的路由
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  const loginStore = useLoginStore()
  if (whiteList.includes(to.path)) {
    //放行
    next()
  } else {
    //需要登录，判断是否登录
    if (loginStore.token) {
      //方向
      next()
    } else {
      //重定向到首页
      next({ path: '/login' })
    }
  }
})

router.afterEach((to, from, next) => {
  NProgress.done()
})
export default router
